// const http = require('http');
const https = require('https');
const express = require('express');
const bodyParser = require('body-parser')
const app = express()
app.use(bodyParser.json({ limit: '100mb' }))
const port = 3000
const { formatTime } = require('./util')

let SQLHelper = require('./SQLHelper');
const res = require('express/lib/response');

SQLHelper('select * from member').then(ret => {
  console.log('i am mysql', ret);
})


// 微信登陆
app.get('/wx/login', (req, res) => {
  let code = req.query.code
  let appid = 'wx4df4bfc7603f4c61'
  let secret = 'e4db34673fb0b4e0e19a66ed440a0b4c'
  https.get(`https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${secret}&js_code=${code}&grant_type=authorization_code`, (ret) => {
    ret.on('data', (ret) => {
      ret = JSON.parse(ret.toString())
      let openid = ret.openid
      if (!openid) {
        res.send({ errorMsg: ret.errMsg || '获取openid错误' })
      } else {
        let queryMember = `select * from member where openId = '${openid}'`
        SQLHelper(queryMember).then(membersRet => {
          if (membersRet.length) {//用户已经存在
            res.send(membersRet[0])
          } else {//用户不存在,使用openid注册用户
            SQLHelper(`INSERT INTO member(openId) VALUES('${openid}')`).then(newMember => {
              //注册成功返回新用户
              SQLHelper(queryMember).then(newMember => {
                res.send(newMember[0])
              })
            })
          }
        })
      }
      // res.send(ret.toString())
    });

  }).on('error', (e) => {
    console.error(e);
    res.send({ errorMsg: '获取openid错误' })
  });
})
//修改用户信息
app.put('/wx/member', (req, res) => {
  let userInfo = req.body
  console.log(req.body)
  SQLHelper(`
  UPDATE member
  set nickName = '${userInfo.nickName}',avatarUrl = '${userInfo.avatarUrl}'
  where _id = '${userInfo._id}'
  `).then(ret => {
    console.log(ret)
    res.send({})
  })
})


//获取收货地址列表
//memberId 用户ID 必填
app.get('/wx/address', (req, res) => {
  console.log(req.query)
  if (req.query.memberId) {
    SQLHelper(`
    select * from address where state = 1 and memberId = ${req.query.memberId}
    `).then(ret => {
      // console.log(ret)
      res.send(ret)
    })
  } else {
    res.send({ errorMsg: '请输入memberId' })
  }
})

//获取收货详情
//addressId 地址_id 必填
app.get('/wx/address/detail', (req,res) => {
  if (req.query.addressId) {
    SQLHelper(`
    select * from address where _id = ${req.query.addressId}
    `).then(ret => {
      // console.log(ret)
      res.send(ret.length ? ret[0] : {errorMsg:'未获取到地址详情'})
    })
  } else {
    res.send({ errorMsg: '请输入addressId' })
  }
})

//新增收货地址
//memberId 用户ID 必填
//receiver 收货人 必填
//phone 手机号 必填
//city 省市区 必填
//area 详细地址 非必填
app.post('/wx/address', (req, res) => {
  if (req.body.memberId && req.body.receiver && req.body.phone && req.body.city) {
    SQLHelper(`
    INSERT INTO address(state,memberId,receiver,phone,city,area)
    VALUES(1,'${req.body.memberId}','${req.body.receiver}','${req.body.phone}','${req.body.city}','${req.body.area || 'null'}')
    `).then(ret => {
      res.send(ret)
    })
  } else {
    res.send({ errorMsg: '传入参数错误' })
  }
})

///修改收货地址
///addressId 地址_ID 必填
///receiver 收货人 非必填
///phone 手机号 非必填
///city 省市区 非必填
///area 详细地址 非必填
app.put('/wx/address',(req,res) => {
  if(req.body.addressId){
    //let sql = 'UPDATE address set '
    let updateKey = ['receiver','phone','city','area']
    let updateValues = []
    for(let i = 0;i < updateKey.length;i++){
        let key = updateKey[i],value = req.body[key]
        if(value) updateValues.push(`${key}='${value}'`)///判断哪些需要修改
    }
    SQLHelper(`UPDATE address set ${updateValues.join(',')} WHERE _id = ${req.body.addressId}`).then(ret => {
         res.send(ret)
      })  
  }else{
    res.send({errorMsg:'传入参数错误'})
  }
})



//修改为默认地址
//addressId 主码_id 必填
//memberId 用户_id 必填
//isDefault 是否默认 非必填
app.put('/wx/address/default', (req, res) => {
  let addressId = req.body.addressId, memberId = req.body.memberId,isDefault = req.body.isDefault == 1 ? 1 : 0
  if (addressId) {
    if (isDefault = 1) {//设置默认地址
      //取消其他默认地址
      SQLHelper(`
      UPDATE address
      set isDefault = 0
      WHERE isDefault = 1 AND memberId = ${memberId}
      `).then(ret => {
        SQLHelper(`
        UPDATE address
        set isDefault = 1
        WHERE _id = ${addressId}
        `).then(ret => {
              res.send(ret)
        })
      })
    }else{//取消默认地址
      SQLHelper(`
      UPDATE address
      set isDefault = 0
      WHERE _id = ${addressId}
      `).then(ret => {
            res.send(ret)
        })
    }
  } else {
    res.send({ errorMsg: '传入参数错误' })
  }
})


//删除地址 逻辑删除
//memberId 用户ID 必填
app.delete('/wx/address', (req, res) => {
  let addressId = req.body.addressId
  if (addressId) {
      SQLHelper(`
      UPDATE address
      set state = 0
      WHERE _id = ${addressId}
      `).then(ret => {
          res.send(ret)
        })
  } else {
    res.send({ errorMsg: '传入参数错误' })
  }
})




app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})
